<template>
  <a-modal title="修改密码" title-align="start" v-model:visible="showvisible" @cancel="showvisible = false" :width="500">
    <a-form :model="form" auto-label-width :rules="rules" ref="formRef">
      <a-form-item label="请输入原密码：" field="oldLoginPwd">
        <a-input v-model="form.oldLoginPwd" placeholder="请输入" allow-clear />
      </a-form-item>
      <a-form-item label="请输入密码：" field="loginPwd">
        <a-input v-model="form.loginPwd" placeholder="请输入" allow-clear />
      </a-form-item>
      <a-form-item label="请再次确认密码：" field="newLoginPwd">
        <a-input v-model="form.newLoginPwd" placeholder="请输入" allow-clear />
      </a-form-item>
    </a-form>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确认</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue'
  import { updateUserPwd } from '@/api/system'
  import { Message } from '@arco-design/web-vue'

  let props = defineProps(['modelValue', 'id'])
  let emits = defineEmits(['update:modelValue', 'save'])

  const loginPwdvalidator = (val: any, callback: any) => {
    if (!val) {
      callback('请填写密码')
    } else if (!val.replace(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/g, '')) {
      callback()
    } else {
      callback('密码格式要求，6位以上包含字母和数字')
    }
  }

  const form: any = ref({})
  const formRef = ref()
  const rules: any = ref({
    oldLoginPwd: [{ required: true, message: '请输入原密码' }],
    loginPwd: [{ required: true, validator: loginPwdvalidator }],
    newLoginPwd: [{ required: true, validator: loginPwdvalidator }],
  })
  let submitLoading = ref(false)
  let showvisible: any = computed({
    set(val) {
      emits('update:modelValue', val)
    },
    get() {
      return props.modelValue
    },
  })

  const submit = async () => {
    const valid = await formRef.value.validate()
    if (!valid) {
      if (form.value.loginPwd !== form.value.newLoginPwd) return Message.error('两次密码输入不一致')
      try {
        submitLoading.value = true
        form.value.id = props.id
        await updateUserPwd(form.value)
        Message.success('密码修改成功')
        showvisible.value = false
        emits('save')
      } catch (error) {}
      submitLoading.value = false
    }
  }
</script>

<style lang="less" scoped></style>
